package serviceModel;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URL;
import serverMessage.ServerMessage;

/**
 * This class is responsible to get message from the server to the client
 */
public class GetSharedFiles implements Runnable{
	
	private static GetSharedFiles getSharedFiles = new GetSharedFiles(); //an instance of this class
	private String host = "localhost"; 
	private ObjectInputStream inObject;
	private PrintWriter out;
	private String userID; //the user id
	private String dropboxPath; //the path of the dropbox folder
	private boolean stopped; //flag- if the thread was stopped
	
	//private ctor
	private GetSharedFiles() {
	}
	
	/**
	 * 
	 * @return an instance of this class
	 */
	public static GetSharedFiles getInstance()
	{
		return getSharedFiles;	
	}

	
	/**
	 * This method responsible to creates a connection from the client to the server (socket)
	 * in order to gets messages from the server, and updates the dropbox folder. 
	 */
	@Override
	public void run() {
		
		
        String requestUrl = "http://localhost:12/WaitForMessageServlet/"+userID;
        Socket socket=null;
        URL url;
        BufferedReader in;
        
        while (!stopped)
        {
        	try {
	        
        		System.out.println("send wait req");
	            url = new URL(requestUrl.toString());
	            in = new BufferedReader(new InputStreamReader(url.openStream()));
	            
	            System.out.println("resumed..");
	            in.close();
	            
	            if (stopped)
	            	break;
	            
	            
	            System.out.println("client socket to server 5555");
	            socket = null;
	            
	            //creates a new socket
			    socket = new Socket(host,5555);
			    out = new PrintWriter(socket.getOutputStream(),true);
			    inObject = new ObjectInputStream(socket.getInputStream());
			    
			    out.println(userID);
	
			    //do all the requests it should do
			    ServerMessage message = (ServerMessage) inObject.readObject();
			    
			    while ((message!=null) && (!message.getKindRequest().equals("bye")))
			    {
			    	//if it is a new folder 
			    	if (message.getKindRequest().equals("create_folder")) {
			    		File file = new File(dropboxPath+"\\"+message.getFolderName());
			    		file.mkdir();
			    		
			    	//if it is a new file in the dropbox folder
			    	} else if (message.getKindRequest().equals("create_file_in_dropbox")) {
			    		convByteToFile(message.getByteFile(),dropboxPath+"\\"+message.getFileName() );
			    	
			    	//if it is a new file in a sub-folder of the dropbox folder
			    	} else if (message.getKindRequest().equals("create_file")) {
			    		convByteToFile(message.getByteFile(),dropboxPath+"\\"+message.getFolderName()+"\\"+message.getFileName() );
			    	
			    	//deletes file
			    	} else if (message.getKindRequest().equals("delete_file")) {
			    		File file = new File(dropboxPath+"\\"+message.getFolderName()+"\\"+message.getFileName() );
			    		if (file.exists())
			    			file.delete();			    		
			    	
			    	//change existing file	
			    	} else if (message.getKindRequest().equals("modify_file")) {
			    		convByteToFile(message.getByteFile(),dropboxPath+"\\"+message.getFolderName()+"\\"+message.getFileName() );			    		
			    	}
			    	
			    	
			    	System.out.println(message);
			    	//reads the next message
			    	message = (ServerMessage) inObject.readObject();	     
			    }
		    
		    
	        } catch (ClassNotFoundException e) {
				System.out.println("get shared files");
				e.printStackTrace();
			} 
	        catch (IOException e) {
				System.out.println("get shared files");
				e.printStackTrace();
			}
	        
			finally {
				
				// close connection (Order important)
				if (out!=null)				
					out.close();
				
				try {
					if (inObject!=null)
						inObject.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				try {
					if (socket!=null)
						socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
								
			}        
	            
	        
        } //end while
    }//end run

	/**
	 * This method finishes the reading of messages from the server 
	 */
	public void stopRun() {
		    stopped = true;    
		    
	}
	
	/**
	 * 
	 * @param userID the userID of the user we want to update his dropbox
	 */
	public void setUserID(String userID) {
		this.userID = userID;
	}

	/**
	 * 
	 * @param dropboxPath the user dropobox's path
	 */
	public void setDropboxPath(String dropboxPath) {
		this.dropboxPath = dropboxPath;
	}
	
	private File convByteToFile(byte[] bytes, String path)
	{	
		//creates a new file
	    File newFile = new File(path);
	    FileOutputStream fos = null;
	    
	    //converts the byte to a file object
		 try {
			 fos = new FileOutputStream(newFile);
			 fos.write(bytes);
			 fos.flush();
			 fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}      
	    
	    return newFile;
	}

	

}
